var MapIndex = {
	overlay:{
		areaOverlay:[],
		myOverlay:[],
		markerClustererLayer:null
	},
	map:null,
	init:function(){
		 var me =this;
		 var operation = sbl.getParameter("operation");
		 me.switchTopPabel(true);
		 me.switchRightPabel(true);
		 me.initLayout();
		 
		 PoliceMap.init(MapIndex);
		 PoliceWorkMap.init(MapIndex);
		 PoliceCaseMap.init(MapIndex);
		 
		 if(operation && operation != ""){
			 
			 if(operation == "showApartmentInMap"){
				 var id = sbl.getParameter("id");
				 me.initBaseMap(19);
				 PoliceWorkMap.showApartmentInfoWindows(null,id);
			 }
			 else if(operation == "showPoliceInMap"){
				 $("ul[tag='jl'] li").removeAttr("selected");
				 $("ul[tag='jl'] li").removeClass("selected");
				 me.initBaseMap(19);
				 $("#listDivSwitch").hide();
				 $("#map_list_table_div").hide();
				 PoliceMap.showPoliceInMap("113.898081", "22.57372", me);
			 }
			 else if(operation == "showPoliceDW"){
				 var dw = sbl.getParameter("dw");
				 var dwli = $("ul[tag='jl'] li[tag='"+dw+"']");
				 if(dwli.length > 0){
					 $("ul[tag='jl'] li").removeAttr("selected");
					 $("ul[tag='jl'] li").removeClass("selected");
					 dwli.attr("selected","selected");
					 dwli.addClass("selected");
				 }
				 me.initBaseMap();
				 me.reloadMapOverlay();		 
				 me.showMapInfoDiv();
				 $("#map_list_table_div").show();
				 $("#listDivSwitch").html("关闭列表");
			 }
		 }
		 else{
			 me.initBaseMap();
			 me.reloadMapOverlay();		 
			 me.showMapInfoDiv();
		 }
		 
		 me.initEvent();		
	},
	initLayout:function(){
		$("div[under], div[tag='z2'], div[tag='z3'], div[tag='z4']").hide();
	},
	initEvent:function(){
		var boss = this;
		
		$("#into_back").bind("click", function(){
			$(this).attr("href", burl + "/view/manager/main.jsp?action=UserList");
		});
		
		$("#exit_session").bind("click", function(){
			sbl.ajax({
				url: burl + "/User/Exsit.do",
				data: {},
				success: function(d){
					alert(d.msg);
					window.location.href = burl + "/view/login.jsp";
				}
			});
		});
		
		$(".menuTitle").bind("click",function(){
			var ul = $(this).next("ul");
			if(ul.is(":hidden")){
				$(".menuList").hide(300);
				ul.show("300");
			}
			else{
				ul.hide("300");
			}
		});
		
		$(".menuList li").bind("click",function(){
			$(".menuList li").removeClass("selected");
			$(".menuList").removeAttr("selected");
			if($(this).hasClass("selected")){
				$(this).removeClass("selected");
			}
			else{
				$(this).addClass("selected");
			}
			
			$(".menuList li.selected").parent().attr("selected","selected");
			boss.reloadMapOverlay(true);
			boss.showMapInfoDiv();
		});
		
		$(".menuTitle .selectAll").bind("click",function(event){
			
			var selectAll = $(this).attr("selectAll");
			var ul = $(this).parent("p").parent("div").children(".menuList");
			$(".menuList").removeAttr("selected");
			$(".menuList li").removeClass("selected");
			if(!selectAll){
				ul.attr("selected","selected");
				ul.children("li").addClass("selected");
				$(this).html("取消");
				$(this).attr("selectAll","selectAll");
			}
			else{
				ul.removeAttr("selected");
				ul.children("li").removeClass("selected");
				$(this).html("全选");
				$(this).removeAttr("selectAll","selectAll");
			}
			event.stopPropagation();
			boss.reloadMapOverlay(true);
		});
		
		$("#panel_switch").bind("click",function(){
			if($(this).hasClass("panel_open")){
				$(this).removeClass("panel_open");
				$(this).addClass("panel_close");
				boss.switchRightPabel(true);
			}
			else{
				$(this).removeClass("panel_class");
				$(this).addClass("panel_open");
				boss.switchRightPabel(false);
			}
		});
		
		$("#shouqi").bind("click",function(){
			if($(this).attr("close")){
				$(this).removeAttr("close");
				$(this).html("全屏");
				boss.switchTopPabel(true);
				boss.switchRightPabel(true);
			}
			else{
				$(this).attr("close","close");
				$(this).html("返回");
				boss.switchTopPabel(false);
				boss.switchRightPabel(false);
			}
		});
		
		$("#tab li").bind("click", function(){
			var tab = $(this).attr("tag");
			var fullid = $("#xuanxiangka div[tag^='z'][selected]").last().attr("fullid");
			window.location.href = burl + "/view/main.jsp?tab=" + tab+"&fullid="+fullid;
		});
		
		$(".map_list_title").bind("click",function(){
			var dw = $(this).attr("dw");
			var ul = $("#list_div_context ul[dw='"+dw+"']");
			if(ul.is(":hidden")){
				ul.show(300);
			}
			else{
				ul.hide(300);
			}
		});
		
		$("#listDivSwitch").bind("click",function(){
			if($("#map_list_table_div").is(":hidden")){
				$("#map_list_table_div").show();
				$("#listDivSwitch").html("关闭列表");
			}
			else{
				$("#map_list_table_div").hide();
				$("#listDivSwitch").html("打开列表");
			}
		});
		
		$("#map_list_sendorder_btn").bind("click",function(){
			prompt("请输入指令","");
		});
		
		 var fullid = sbl.getParameter("fullid");
		
		orgSelecter.initOrgSelecter(function(){
			boss.reloadMapOverlay();
			boss.showMapInfoDiv();
			var mapx = $("#xuanxiangka div[tag^='z'][selected]").last().attr("mapx");
			var mapy = $("#xuanxiangka div[tag^='z'][selected]").last().attr("mapy");
			var zoom = parseInt($("#xuanxiangka div[tag^='z'][selected]").last().attr("zoom"));
			if(mapx > 1){
				var center = new BMap.Point(mapx,mapy);
				boss.map.centerAndZoom(center, zoom);
			}
			
		},boss,fullid);
		
		$("#DispatchCtrl").bind("click",function(){
//			var center = new BMap.Point(113.906793,22.563063);
//			boss.map.centerAndZoom(center, 17);
//			PoliceMap.startDispatch();
			PoliceMap.showSingle = true;
			PoliceMap.renderLayer();
		});
	},
	initBaseMap:function(zoom){
		var boss = this;
        if(!zoom){
        	zoom = 15;
        }
		boss.map = new BMap.Map("mapDiv");    
		boss.map.centerAndZoom(new BMap.Point(113.895367, 22.56343), zoom);
		boss.map.addControl(new BMap.MapTypeControl());
		boss.map.enableScrollWheelZoom();
		
		var myZoomCtrl = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div class='quanping' id='shouqi'>全屏</div>");
		boss.map.addControl(myZoomCtrl);
		var DispatchCtrl = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div id='DispatchCtrl'>指挥调度</div>");
		boss.map.addControl(DispatchCtrl);
		var listDivSwitch = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div id='listDivSwitch'>打开列表</div>");
		boss.map.addControl(listDivSwitch);
		var mapListDiv = new MyMapControl(BMAP_ANCHOR_TOP_RIGHT,20, 40,"<div id='map_list_table_div'></div>");
		boss.map.addControl(mapListDiv);
		$("#shouqi,#map_list_table_div,#listDivSwitch,#DispatchCtrl").removeAttr("style");
		$("#map_list_table_div").html($("#temcontent").html());
		$("#map_list_table_div").hide();
		$("#temcontent").remove()
		
		boss.map.addEventListener("zoomend", boss.reloadMapOverlay);
//		boss.map.addEventListener("click", function(e){
//			//alert(e.point.lng+","+e.point.lat);
//		});
		boss.map.boss = boss;
	},
	reloadMapOverlay:function(force){
		var boss = this.boss;
		if(!boss){
			boss = this;
		}
		var zoom = boss.map.getZoom();
		var selectMenu = $(".menuList[selected]").attr("tag");
		var controller = $(".menuList[selected]").attr("controller");
		boss.map.closeInfoWindow();
		boss.clearMapOverLay();
		boss.reloadAreaLayer();
		eval(controller+"Map.renderLayer()");
	},
	reloadAreaLayer:function(){
		var boss = this;
		var zoom = boss.map.getZoom();
		boss.clearAreaOverlay();
		boss.overlay.areaOverlay = [];
		
		var fullid = $("#xuanxiangka div[tag^='z'][selected]").last().attr("fullid");
		var isstreet = $("#xuanxiangka div[tag^='z'][selected]").last().attr("isstreet");
		var zoomLevel = boss.getZoomLevel();
		if(isstreet != "1"){
			if(zoomLevel == "baoan"){
				//宝安分局
				boss.loadAreaLayer("0-1-","2",fullid,null,"red");
			}
			else if(zoomLevel == "paichusuo"){
				//派出所
				boss.loadAreaLayer("0-1-","3",fullid,null,"red");
			}
			else if(zoomLevel == "jingqu"){
				//派出所和警区
				boss.loadAreaLayer(orgSelecter.getPaichusuoFullid(),"4",fullid,null,"blue");
			}
			else if(zoomLevel == "zerenqu"){
				//派出所和责任区
				boss.loadAreaLayer(orgSelecter.getPaichusuoFullid(),"5",fullid,null,"blue");
			}
		}
		else{
			if(zoom <= 14){
				//宝安分局
				boss.loadAreaLayer(orgSelecter.getPaichusuoFullid(),"3",fullid,null,"red");
			}
			else {
				//街道办
				boss.loadAreaLayer(orgSelecter.getPaichusuoFullid(),"4",fullid,null,"red");
			}
		}
	},
	loadCenterLayer:function(url,data,unit,onMouseOver,onMarkerRender){
		var boss = this;
		var daleis = $(".menuList[selected]");
		sbl.ajax({
			dataType:'json',
			type:'get',
			url:url,
			data:data,
			success:function(d){
				var data = d;
				var zoom = boss.map.getZoom();
				for(var jindex in data){
					var row = data[jindex];
					
					var points = [];
					var lonlats;
					
					if(row.MAPXY){
						lonlats = row.MAPXY.split(";")
					}
					else if(row.X){
						lonlats = [row.X+","+row.Y];
					}
					else if(row.MAPX){
						lonlats = [row.MAPX+","+row.MAPY];
					}
					else{
						continue;
					}
					
					for(var j =0;j<lonlats.length;j++){
						var lonlat = lonlats[j].split(",");
						var lon = lonlat[0];
						var lat = lonlat[1];
						var point = new BMap.Point(lon,lat);
						points.push(point);
					}
					var polygon = new BMap.Polygon(points);
					var point = polygon.getBounds().getCenter();
					var Marker ;
					if(onMarkerRender){
						Marker = onMarkerRender.call(boss,point,row,jindex,zoom);
					}
					else{
						
						var imgUrl = burl+"/images/map/jj.png";
						if(zoom < 18){
							imgUrl = burl+"/images/map/jj.png";
						}
						else{
							imgUrl = burl+"/images/map/xiaoqu.png";
						}
						Marker = new BMap.Marker(point);
						Marker.data = row;
						var icon = new BMap.Icon(burl+"/images/map/5.png", new BMap.Size(120,120));
						var count = parseInt(row.COUNT);
						var labelContent = "<div class='centerDiv'>";		
						labelContent += "<img width='70' height='50' src='"+imgUrl+"' /><br/>";
						labelContent += row.DEPTNAME+"<br><span style='font-size:20px'>"+row.COUNT + unit+"</span><br/>";
						labelContent += "</div>";
						var label = new BMap.Label(labelContent,{offset:new BMap.Size(12,8)});
						label.setStyle({"borderWidth":"0px","background":"","color":"white","fontSize":"14px"});
						Marker.setLabel(label);
						Marker.setIcon(icon);
					}					
					Marker.mouseOutIcon = Marker.getIcon();
					boss.map.addOverlay(Marker);
					boss.overlay.myOverlay.push(Marker);
					Marker.addEventListener("click",function(){
						var zoom = boss.map.getZoom();
						var center = new BMap.Point(this.point.lng,this.point.lat);
						boss.map.centerAndZoom(center, zoom+1);
					});
					Marker.addEventListener("mouseover",function(){
						var icon = new BMap.Icon(burl+"/images/map/51.png", new BMap.Size(120,120));
						this.setIcon(icon);
						if(onMouseOver){
							onMouseOver.call(this);
						}
					});
					Marker.addEventListener("mouseout",function(){
						var icon = this.mouseOutIcon;
						this.setIcon(icon);
						boss.map.closeInfoWindow();
					});
				}
			}
		});			
	},
	loadStreetCenterLayer:function(url,data,unit,onMouseOver,onMarkerRender){
		var boss = this;
		sbl.ajax({
			dataType:'json',
			type:'get',
			url:url,
			data:data,
			success:function(d){
				var data = d;
				data
				var zoom = boss.map.getZoom();
				var polygon = boss.getConbitePolygon(data);
				var point = polygon.getBounds().getCenter();
				boss.map.centerAndZoom(point, zoom);
				var Marker = boss.MarkerJingqing(point,data,1,zoom);
				Marker.mouseOutIcon = Marker.getIcon();
				boss.map.addOverlay(Marker);
				boss.overlay.myOverlay.push(Marker);
				Marker.addEventListener("click",function(){
					var zoom = boss.map.getZoom();
					var center = new BMap.Point(this.point.lng,this.point.lat);
					boss.map.centerAndZoom(center, zoom+1);
				});
				Marker.addEventListener("mouseover",function(){
					var icon = new BMap.Icon(burl+"/images/map/51.png", new BMap.Size(120,120));
					this.setIcon(icon);
					if(onMouseOver){
						onMouseOver.call(this);
					}
				});
				Marker.addEventListener("mouseout",function(){
					var icon = this.mouseOutIcon;
					this.setIcon(icon);
					boss.map.closeInfoWindow();
				});
			}
		});	
	},
	loadAreaLayer:function(fullid,requeslevel,currentFullid,colorAttr,strokeColor){
		var boss = this;
		var bound = boss.map.getBounds();
		var miny = bound._swLat;
		var minx = bound._swLng;
		var maxy = bound._neLat;
		var maxx = bound._neLng;
		var isstreet = $("#xuanxiangka div[tag^='z'][selected]").last().attr("isstreet");
		var url = "";
		
		if(isstreet == "1"){
			url = burl+"/StreetDept/getOrgByLevel.do";
		}
		else{
			url = burl+"/Dept/getOrgByLevel.do"
		}
		
		sbl.ajax({
			dataType:'json',
			type:'get',
			data:{miny:miny,minx:minx,maxy:maxy,maxx:maxx,fullid:fullid,level:requeslevel},
			url:url,
			success:function(dd){
				var data;
				if(!dd.length){
					data = [dd];
				}
				else{
					data = dd;
				}
				var parentFullid = boss.getParentFullid(currentFullid);
				var selectedOrgLevel = boss.zoomLevelMapper[boss.getFullidLevel(currentFullid)];
				for(var i=0;i<data.length;i++){
					var d = data[i];
					var colorIndex = parseInt(d.fullid[d.fullid.length-2]);
					var points = [];
					var lonlats = d.mapxy.split(";");
					
					for(var j =0;j<lonlats.length;j++){
						var lonlat = lonlats[j].split(",");
						var lon = lonlat[0];
						var lat = lonlat[1];
						var point = new BMap.Point(lon,lat);
						points.push(point);
					}
					var fillColor = "gray";
					if(selectedOrgLevel > requeslevel){
						if(parentFullid.indexOf(d.fullid) > -1){
							fillColor = "";
						}
					}
					else if(selectedOrgLevel == requeslevel){
						if(d.fullid == currentFullid){
							fillColor = "";
						}
					}
					else if(selectedOrgLevel < requeslevel){
						if(d.fullid.indexOf(currentFullid)>-1){
							fillColor = "";
						}
					}
					
					var option={fillColor:fillColor,strokeWidth:"5px",fillOpacity:0.4,strokeStyle:"dashed",strokeColor:strokeColor};
					var polygon = new BMap.Polygon(points,option);
					boss.map.addOverlay(polygon);
					polygon.setStrokeWeight(4);
					boss.overlay.areaOverlay.push(polygon);
				}
			}
		});
	},
	clearMapOverLay:function(){
		var boss = this;
		
		if(boss.markerClustererLayer){
			MapIndex.overlay.markerClustererLayer.removeMarkers(boss.overlay.myOverlay);
			MapIndex.overlay.markerClustererLayer.clearMarkers();
		}
		
		for(var i=0;i<boss.overlay.myOverlay.length;i++){
			boss.map.removeOverlay(boss.overlay.myOverlay[i]);
		}
	},
	clearAreaOverlay:function(){
		var boss = this;
		
		for(var i in boss.overlay.areaOverlay){
			boss.map.removeOverlay(boss.overlay.areaOverlay[i]);
		}
	},
	showMapInfoDiv:function(){
		var boss = this;
		var selectedTag = $(".menuList[selected]").attr("tag");
		var fullid = $("#xuanxiangka div[tag^='z'][selected]").last().attr("fullid");
		
		var StatisticsModels = modelDao.getPoliceStatistics(fullid);
		var htmlContent = "<div class='map_info_table_title'>警力信息</div>";
		htmlContent += "<div class='mapCornerWindowWarp' style='display:none'><table class='mapWindowsTable'>";
		var allCount = 0;
		if(!StatisticsModels){
			return;
		}
		for(var i=0;i<StatisticsModels.length;i++){
			var StatisticsModel = StatisticsModels[i];
			if(StatisticsModel.DWNUM){
				
				var label;
				if(StatisticsModel.DWNUM == "6"){
					label = "民警";
				}
				else{
					label = "第"+StatisticsModel.DWNUM+"支队伍";
				}
				htmlContent += "<tr>";
				htmlContent += "<td class='label' style='background-image:url("+burl+"//images//map//team//"+StatisticsModel.DWNUM+".png)'>"+label+":</td><td class='value'>"+StatisticsModel.COUNT+"人</td>";
				htmlContent += "</tr>";
				allCount += StatisticsModel.COUNT;
			}
		}
		htmlContent += "<tr>";
		htmlContent += "<td class='label'>总计:</td><td class='value'>500人</td><td>总计：</td><td>"+allCount+"人</td>";
		htmlContent += "</tr>";
		htmlContent += "</table></div>";
		
		if(selectedTag == "jw"){
			var StatisticsModels = modelDao.getApartmentStatistics(fullid,"1");
			var StatisticsPoliceModels = modelDao.getPoliceStatistics(fullid);
			htmlContent += "<div class='map_info_table_title'>警务信息</div>";
			htmlContent += "<div class='mapCornerWindowWarp' style='display:none'><table class='mapWindowsTable'>";
			allCount = 0;
			for(var i=0;i<StatisticsModels.length;i++){
				var StatisticsModel = StatisticsModels[i];
				if(StatisticsModel.BUILDING_TYPE){
					htmlContent += "<tr class='data'>";
					htmlContent += "<td class='label'>"+StatisticsModel.BUILDING_TYPE+":</td><td class='value'>"+StatisticsModel.COUNT+"栋</td>";
					htmlContent += "</tr>";
					allCount += StatisticsModel.COUNT;
				}
			}
			htmlContent += "<tr>";
			htmlContent += "<td class='label'>总计:</td><td class='value'>"+allCount+"栋</td>";
			htmlContent += "</tr>";
			htmlContent += "</table></div>";
		}
		$("#map_fa_info_table_div").html(htmlContent);
		
		$(".map_info_table_title").bind("click",function(){
			
			var tableDiv = $(this).next();
			var height = $("table",tableDiv).height()
			if(tableDiv.is(":hidden")){
				$(".mapCornerWindowWarp").animate({ 
				    height: "0"
				  }, 10,"linear",function(){
					  $(this).hide();
					  $(this).css("height","");
				  });
				tableDiv.show(300);
			}
			else{
				tableDiv.animate({ 
				    height: "0"
				  }, 300,"linear",function(){
					  $(this).hide();
					  $(this).css("height","");
				  });
			}
		});
	},
	switchRightPabel:function(isOpen){
		var pabelWidth = 212;
		var bodyWidth = document.documentElement.clientWidth;
		var mainWidth = 0;
		
		if(isOpen){
			mainWidth = bodyWidth - pabelWidth - 2;
			$("#filter").show();
		}
		else{
			mainWidth = bodyWidth;
			$("#filter").hide();
		}
		
		$(".main").css("width", mainWidth);
		$(".container").css("width",bodyWidth);
	},
	switchTopPabel:function(isOpen){
		var pabelHeight = 110;
		var bodyHeight = document.documentElement.clientHeight;
		var mainHeight = 0;
		
		if(isOpen){
			mainHeight = bodyHeight - pabelHeight;
			$(".header").show();
		}
		else{
			mainHeight = bodyHeight;
			$(".header").hide();
		}
		
		$(".main,#filter").css("height", mainHeight);
	},
	getParentFullid:function(fullid){
		var fullids = fullid.split("-");
		var result = "";
		
		if(fullids.length > 3){
			for(var i=0;i<fullids.length-2;i++){
				result += fullids[i]+"-"
			}
		}
		return result;
	},
	getZoomLevel:function(){
		var boss = this;
		var zoom = boss.map.getZoom();
		
		if(zoom <= 14){
			return "baoan";
		}
		else if(zoom == 15){
			return "paichusuo";
		}
		else if(zoom == 16){
			return "jingqu";
		}
		else {
			return "zerenqu";
		}
	},
	zoomLevelMapper:{
		baoan:2,
		paichusuo:3,
		jingqu:4,
		zerenqu:5
	},
	getFullidLevel:function(fullid){
		var infos = fullid.split("-");
		if(infos.length == 3){
			return "baoan";
		}
		else if(infos.length == 4){
			return "paichusuo";
		}
		else if(infos.length == 5){
			return "jingqu";
		}
		else if(infos.length == 6){
			return "zerenqu";
		}
	}
};
$(function(){
	MapIndex.init();
});